<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>
    <div id="title">
      <button data-path="/home">首页</button>
      <button data-path="/center">我的</button>
      <button data-path="/hot">热门</button>
    </div>
    <div id="view"></div>
  </div>
  
  <script>
    const oBtns = document.querySelectorAll('#title>button');
    const oView = document.getElementById('view');
    // 路由表
    const routes = [
      { path: '/home', component: '<h2>欢迎来到首页</h2>' },
      { path: '/center', component: '<h2>我真的不是大冤种</h2>' },
      { path: '/hot', component: '<h2>武汉尚硅谷XXX拿到30k offer</h2>' },
    ];
  
    //给所有的button绑定点击事件
    for (var i = 0; i < oBtns.length; i++) {
      oBtns[i].onclick = function () {
        // 调用history对象的pushState方法来添加一个state (路由路径)
        history.pushState(null, null, this.dataset.path);
  
        // 得到手动遍历查找对应的路由组件去更新显示
        routes.forEach((route) => {
          if (route.path === this.dataset.path) {
            oView.innerHTML = route.component;
          }
        });
      };
    }
  
    // 监视浏览器的前进和回退的, 不能监视pushState导致的变化
    window.onpopstate = function () {
      console.log(location.pathname);
      routes.forEach((route) => {
        if (route.path === location.pathname) {
          oView.innerHTML = route.component;
        }
      });
    };
  </script>
</body>
</html>